<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class CategoryController extends Controller
{

 //后台显示产品分类
 public function getIndex()
 {
    //查询分类栏目
    $res = DB::select("select *,concat(path,id) as pathid from ym_category order by pathid asc");
    return view('admin/Category',['category'=>$res]);
 }

 //显示添加商品分类
 public function getAdd(Request $request)
 {
      $id = $request->input('id','0');
      $name = $request->input('name','顶级分类');
      return view('admin/CategoryAdd',['pname'=>$name,'pid'=>$id]);
 }

 //插入分类数据
 public function postInsert(Request $request)
 {
     //接收pid
     $data['pid'] = $request->input('pid');
     //判断是顶级分了还是子分类
     if($data['pid']==0){
        //如果是t添加顶级分类
        $data['path'] = '0,';
     }else{
     //如果是添加子分类
     //查询pid得到path
     $res = DB::table('ym_category')->where('id',$data['pid'])->first();
     $data['path'] = $res->path.$data['pid'].',';
     }

     //分类名称
     $data['name'] = $request->input('categoryname');
     //查询数据库判断分类名称是否存在
     $res1 = DB::table('ym_category')->where('name',$data['name'])->first();
     //插入数据
     $res2 = DB::table('ym_category')->insert($data);
     //如果分类名称为空
     if(empty($res1->id)){
        //如果插入成功
         if($res2 == 1){
            return redirect('/admin/category/index')->with('success','分类添加成功');
         }else{
            return back()->with('error','分类添加失败');
         }
     }else{
            return back()->with('error','分类名称已经存在');
     }

 }

 //修改产品分类模板
   public function getShowedit(Request $request)
   {
      //接收产品分类id
      $data = $request->all();
      return view('admin/CategoryEdit',['category'=>$data]);
   }

//插入修改分类数据
   public function postEdit(Request $request){
    $data = $request->all();
    $res = DB::update("update ym_category set name='{$data['categoryname']}' where id={$data['id']}");
    return redirect('admin/category');
   }

   //删除商品分类

   public function getDelete(Request $request)
   {
     $id = $request->input('id');
     //先判断此分类下面是否有子分类
     $res1 = DB::table('ym_category')->where('pid',$id)->first();
     if(empty($res1->id)){
         //在判断此分类下面是否有产品
        $res3 = DB::table('ym_category')->where('id',$id)->delete();
        if($res3){
            echo '分类删除成功'; 
        }
     }else{
        echo '此栏目下面有子栏目,不能删除';
     }
   }
//--------------------------------------------
   public function getTest()
   {
      $res = $this->getDg(0);
      dd($res);
   }
   public function getDg($id)
   {
      $res = DB::table('ym_category')->where('pid',$id)->get();
      foreach($res as $k=>$v){
         $res[$k]->sub = $this->getDg($v->id);
      }
      return $res;
   }
}
